package com.example.UserRegistration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import jakarta.validation.constraints.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String home() {
        return "redirect:/register";
    }

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(@ModelAttribute User user, BindingResult result, Model model) {
        logger.info("接收到注册请求：{}", user.getEmail());
        
        if (result.hasErrors()) {
            logger.error("表单绑定错误: {}", result.getAllErrors());
            model.addAttribute("error", "表单数据无效，请检查后重试");
            return "register";
        }
        
        try {
            userService.registerUser(user);
            logger.info("用户注册成功：{}", user.getEmail());
            // 注册成功后跳转到成功页面
            return "registerSuccess";
        } catch (IllegalArgumentException e) {
            logger.error("注册失败：{}", e.getMessage());
            model.addAttribute("error", "邮箱已存在");
            return "register";
        } catch (Exception e) {
            logger.error("注册过程中发生错误", e);
            model.addAttribute("error", "注册过程中发生错误：" + e.getMessage());
            return "register";
        }
    }
}